package msg

import (
	"context"
	"fmt"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	uuid "github.com/satori/go.uuid"
	"go-zero-project/services/user/api/constans"

	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderMsgLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderMsgLogic {
	return &OrderMsgLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderMsgLogic) OrderMsg(req *types.SendOrderMsgReq) (resp *types.SendOrderMsgResp, err error) {
	msgArr := req.MsgArr
	shardKey := uuid.NewV4()
	for _, v := range msgArr {
		// covert request
		bodyByte := []byte(v)
		message := primitive.Message{Topic: constans.UserOrderTopic, Body: bodyByte}
		message.WithTag("order")
		message.WithShardingKey(fmt.Sprintf("%d", shardKey))
		message.WithKeys([]string{uuid.NewV4().String()})
		// send msg
		sendResult, sendErr := l.svcCtx.DefaultProducer.SendSync(l.ctx, &message)
		if sendErr != nil {
			return nil, sendErr
		}
		logx.Infof("msgId %s,topic:%s,send msg:%s!", message.Topic,
			sendResult.MsgID, string(message.Body))
	}
	// return obj
	return &types.SendOrderMsgResp{
		Topic:  constans.UserOrderTopic,
		Tag:    "order",
		MsgArr: msgArr,
	}, nil
}
